package cn.harry.modular.news.service.impl;

import cn.harry.modular.news.domain.Answer;
import cn.harry.modular.news.domain.News;
import cn.harry.modular.news.service.AnswerService;
import cn.harry.modular.news.service.FeedbackService;
import cn.harry.modular.news.service.HomeService;
import cn.harry.modular.news.service.NewsService;
import cn.harry.modular.news.vo.CountVO;
import cn.harry.modular.news.vo.EchartsOptionVO;
import cn.harry.modular.system.service.SysUserService;
import cn.hutool.json.JSONArray;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author harry
 * @公众号 Harry技术
 */
@Service
@AllArgsConstructor
public class HomeServiceImpl implements HomeService {
    private final NewsService newsService;
    private final AnswerService answerService;
    private final FeedbackService feedbackService;
    private final SysUserService sysUserService;


    @Override
    public List<CountVO> counts() {
//        新闻总数 问答总数 反馈总数 用户总数
        CountVO newsCount = new CountVO();
        newsCount.setCount(newsService.count());
        newsCount.setName("新闻总数");
        CountVO answerCount = new CountVO();
        answerCount.setCount(answerService.count());
        answerCount.setName("问答总数");
        CountVO feedbackCount = new CountVO();
        feedbackCount.setCount(feedbackService.count());
        feedbackCount.setName("反馈总数");
        CountVO userCount = new CountVO();
        userCount.setCount(sysUserService.count());
        userCount.setName("用户总数");
        return List.of(newsCount, answerCount, feedbackCount, userCount);
    }

    @Override
    public EchartsOptionVO userAnswerCounts() {
        EchartsOptionVO echartsOptionVO = new EchartsOptionVO();
        List<Answer> list = answerService.list();
        Map<String, List<Answer>> map = list.stream().collect(
                Collectors.groupingBy(Answer::getUserName)
        );
        echartsOptionVO.setXData(new JSONArray(map.keySet()));
        echartsOptionVO.setYData(new JSONArray(map.values().stream().map(List::size).toList()));
        return echartsOptionVO;
    }

    @Override
    public List<CountVO> newsCategoryCounts() {
        List<News> list = newsService.list();
        Map<String, List<News>> map = list.stream().collect(
                Collectors.groupingBy(News::getType)
        );
        if (!map.isEmpty()) {
            return map.entrySet().stream().map(entry -> {
                CountVO countVO = new CountVO();
                countVO.setName(entry.getKey());
                countVO.setCount((long) entry.getValue().size());
                return countVO;
            }).toList();
        }
        return List.of();
    }
}
